import axios from 'axios';
import router from '../router/index.js';
import { ElMessage } from 'element-plus';

let tokenError = false;

const services = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, //import.meta.env.VITE_BASE_API
  timeout: 800000
})
// 请求拦截
services.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

services.interceptors.response.use(
  response => {
    console.log(response)
    let token = response.headers["authorization"];
    if (token) {
      localStorage.setItem('token', token)
    }
    
    if (response.config.responseType === 'blob') {
      const blob1 = new Blob([response.data], {
        type: 'application/json'
      })
      const reader = new FileReader()
      reader.readAsText(blob1)
      reader.onloadend = (data) => {
        const str = data.target.result
        if (str.slice(0, 1) === '{') {
          let data = JSON.parse(str)
          if (data.code === 401) {
            localStorage.clear();
            if (!tokenError) {
              const msg = data.message || "您的凭证已过期，请重新登录。"
              ElMessage.error({ message: msg, duration: 10000 });
              tokenError = true;
            }
            router.push('/login');
          } else if (data.code === 403) {
            if (!tokenError) {
              const msg = data.message || "您还没有权限，请联系管理员。"
              ElMessage.error({ message: msg, duration: 10000 });
              tokenError = true;
            }
            router.push('/403');
          } else {
            const msg = data.message || 'Upload Error';
            ElMessage.error({ message: msg, duration: 10000 });
          }
        }
      }
      return response;
    } 
    const res = response.data
    if (res.code && res.code !== 200) {
      if (res.code == 401) {
        localStorage.clear();
        if (!tokenError) {
          const msg = res.message || "您的凭证已过期，请重新登录。"
          ElMessage.error({ message: msg, duration: 10000 });
          tokenError = true
        }
        router.push('/login');
        return res
      }
      else if (res.code === 403) {
        // localStorage.clear();
        if (!tokenError) {
          const msg = res.message || "您还没有权限，请联系管理员。"
          ElMessage.error({ message: msg, duration: 10000 });
          tokenError = true
        }
        // router.push('/login');
        // router.push('/403');
        return res
      } else {
        const msg = res.message || 'Error'
        ElMessage.error({ message: msg, duration: 10000 });
        return res
      }
    } else {
      tokenError = false
    }
    return res
  },
  error => {
    console.log(error)
    if (error.response) {
      if (error.response.status === 401) {
        if (!tokenError) {
          const msg = error.response.data.message || "您的凭证已过期，请重新登录。"
          ElMessage.error({ message: msg, duration: 10000 });
          localStorage.clear()
          tokenError = true
        }
        router.push('/login');
        return Promise.resolve(error)
      } else if (error.response.status === 403) {
        if (!tokenError) {
          const msg = res.message || "您还没有权限，请联系管理员。"
          ElMessage.error({ message: msg, duration: 10000 });
          tokenError = true
        }
        router.push('/403');
        return Promise.resolve(error)
      } else {
        let msg;
        // 针对上传文件时，先选择文件再变更文件时会axios自动报错,谷歌自动报错，其他不报错
        if (error.response.status === 400 && Object.prototype.toString.apply(error.config.data) === "[object FormData]") {
          msg = "文件内容发生变更，请重新选择文件后上传。";
        } else {
          msg = error.response.data.message || error.response.statusText
        }
        ElMessage.error({ message: msg, duration: 10000 });
        return Promise.resolve(error)
      }
    } else {
      if (error.name !== 'CanceledError' && error.message !== 'Request aborted') {
        let msg;
        // 针对上传文件时，先选择文件再变更文件时会axios自动报错,谷歌自动报错，其他不报错
        if (Object.prototype.toString.apply(error.config.data) === "[object FormData]") {
          msg = "文件内容发生变更，请重新选择文件后上传。";
        } else {
          msg = error.message;
        }
        ElMessage.error({ message: msg, duration: 10000 });
      }
      return Promise.resolve(error)
    }
  }
)

const CancelToken = axios.CancelToken;
export const source = CancelToken.source();
// 使用时携带参数
// { cancelToken: source.token }
// 取消所有带参cancelToken的请求
// source.cancel()

// export default services
export default function request(options) {
  return services(options)
}
